package com.zing.network.net;

import java.io.IOException;
import java.util.List;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author jichang
 * @date 2018/9/19 21:12
 * email: 2218982471@qq.com
 * describ:
 */
public class BaseUrlInterceptor implements Interceptor {

    /**
     * base url
     */
    private static final String WANANDROID = "normal";
    private static final String DOUYU = "douyu";
    private static final String GETLIVE = "live";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        HttpUrl oldUrl = originalRequest.url();
        Request.Builder newBuilder = originalRequest.newBuilder();
        List<String> urlNameList = originalRequest.headers("baseUrl");
        if (urlNameList != null && urlNameList.size() > 0) {
            newBuilder.removeHeader("baseUrl");
            String urlName = urlNameList.get(0);
            HttpUrl baseUrl = null;
            if (WANANDROID.equals(urlName)) {
                baseUrl = HttpUrl.parse(AppConfig.BASE_URL);
            } else if (DOUYU.equals(urlName)) {
                baseUrl = HttpUrl.parse(AppConfig.DOUYU_URL);
            } else if (GETLIVE.equals(urlName)) {
                baseUrl = HttpUrl.parse(AppConfig.GETLIVE_URL);
            }
            HttpUrl newHttpUrl = oldUrl.newBuilder()
                    .scheme(baseUrl.scheme())
                    .host(baseUrl.host())
                    .port(baseUrl.port())
                    .build();
            Request newRequest = newBuilder.url(newHttpUrl).build();
            return chain.proceed(newRequest);
        } else {
            return chain.proceed(originalRequest);
        }
    }
}
